package com.ruoyi.system.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import com.ruoyi.common.config.QiNiuConfig;
import com.ruoyi.common.constant.QiNiuConstant;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.system.domain.vo.QiNiuVo;
import com.ruoyi.system.service.IQiNiuService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @description:
 * @author: yxp
 * @create: 2020/08/07
 * @version: 1.0
 */
@Service
public class QiNiuServiceImpl implements IQiNiuService {
	@Resource
	QiNiuConfig qiNiuConfig;
	@Resource
	private RedisCache redisCache;

	@Override
	public QiNiuVo getToken() {

		Object cacheToken = redisCache.getCacheObject(QiNiuConstant.TOKEN_KEY);
		QiNiuVo qiNiu = new QiNiuVo();
		qiNiu.setCdn(qiNiuConfig.getCdn());
		//如果缓存中没有token
		if (ObjectUtil.isNull(cacheToken)) {
			String accessKey = qiNiuConfig.accessKey;
			String secretKey = qiNiuConfig.secretKey;
			String bucket = qiNiuConfig.bucket;
			Long expireSeconds = qiNiuConfig.expireSeconds;
			Auth auth = Auth.create(accessKey, secretKey);
			//上传策略的其它参数，如 new StringMap().put("endUser", "uid").putNotEmpty("returnBody", "")。
			//scope通过 bucket、key间接设置，deadline 通过 expires 间接设置
			StringMap policy = new StringMap();
			String token = auth.uploadToken(bucket, null, expireSeconds, policy);
			qiNiu.setToken(token);
			redisCache.setCacheObject(QiNiuConstant.TOKEN_KEY, token, Math.toIntExact(expireSeconds), TimeUnit.SECONDS);
		} else {
			String token = redisCache.getCacheObject(QiNiuConstant.TOKEN_KEY);
			qiNiu.setToken(token);
		}
		return qiNiu;
	}
}
